<template>
  <!--面包屑导航-->
  <Breadcrumb>
    <template #firstTitle>
      <span>商品管理</span>
    </template>
    <template #secondTitle>
      <span>参数列表</span>
    </template>
  </Breadcrumb>

  <!--卡片视图-->
  <el-card>
    <!--警告文字-->
    <el-alert
      title="注意：只允许为第三级分类设置相关参数！"
      type="warning"
      show-icon
      :closable="false"
    >
    </el-alert>

    <!--选择商品分类-->
    <el-row class="cat-opt">
      <el-col>
        <span>选择商品分类：</span>
        <!--选择商品分类的连级选择框-->
        <el-cascader
          v-model="selectedKeys"
          :options="cateList"
          :props="cascaderProps"
          @change="parentCateChange"
          clearable
        ></el-cascader>
      </el-col>
    </el-row>

    <!--tab页签-->
    <el-tabs v-model="activeTabName" @tab-click="handleTabClick">
      <el-tab-pane label="动态参数" name="many">
        <el-button type="primary" :disabled="isBtnDisabled" @click="handleAddOrEdit(null)">添加参数</el-button>
        <!--动态参数表格-->
        <el-table border stripe :data="manyTableData" row-key="attr_id" :expand-row-keys="attrId">
          <!--展开列-->
          <el-table-column type="expand">
            <template #default="props">
              <!--循环渲染tag标签-->
              <el-tag
                closable
                v-for="(item, index) in props.row.attr_vals"
                :key="index + item"
                @close="removeParams(props.row, index)"
                >{{ item }}</el-tag>
              <!--输入文本框-->
              <el-input
                class="input-new-tag"
                v-show="props.row.inputVisible"
                v-model="props.row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter="handleInputConfirm(props.row)"
                @blur="handleInputConfirm(props.row)"
              ></el-input>
              <!--添加tag按钮-->
              <el-button
                v-show="!props.row.inputVisible"
                size="small"
                @click="showInput(props.row)"
                class="btn-new-tag"
              >+ New Tag</el-button>
            </template>
          </el-table-column>
          <!--索引列-->
          <el-table-column type="index"></el-table-column>
          <el-table-column prop="attr_name" label="参数名称"></el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <!--编辑按钮-->
              <el-button type="primary" size="small" @click="handleAddOrEdit(scope.row)">编辑</el-button>
              <!--删除按钮-->
              <el-button
                type="danger"
                size="small"
                @click="handleDelete(scope.row.attr_id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>

      <el-tab-pane label="静态属性" name="only">
        <el-button type="primary" :disabled="isBtnDisabled" @click="handleAddOrEdit(null)">添加属性</el-button>
        <!--静态属性表格-->
        <el-table border stripe :data="onlyTableData" row-key="attr_id" :expand-row-keys="attrId">
          <!--展开列-->
          <el-table-column type="expand">
            <template #default="props">
              <!--循环渲染tag标签-->
              <el-tag
                closable
                v-for="(item, index) in props.row.attr_vals"
                :key="index + item"
                @close="removeParams(props.row, index)"
              >{{ item }}</el-tag>
              <!--输入文本框-->
              <el-input
                class="input-new-tag"
                v-show="props.row.inputVisible"
                v-model="props.row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter="handleInputConfirm(props.row)"
                @blur="handleInputConfirm(props.row)"
              ></el-input>
              <!--添加tag按钮-->
              <el-button
                v-show="!props.row.inputVisible"
                size="small"
                @click="showInput(props.row)"
                class="btn-new-tag"
              >+ New Tag</el-button>
            </template>
          </el-table-column>
          <!--索引列-->
          <el-table-column type="index"></el-table-column>
          <el-table-column prop="attr_name" label="属性名称"></el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <!--编辑按钮-->
              <el-button type="primary" size="small" @click="handleAddOrEdit(scope.row)">编辑</el-button>
              <!--删除按钮-->
              <el-button
                type="danger"
                size="small"
                @click="handleDelete(scope.row.attr_id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
  </el-card>

  <addOrEditParam
    v-model="isShowVisible"
    v-model:attrInfo="attrInfo"
    v-model:titleText="titleText"
    v-model:activeTabName="activeTabName"
    v-model:cateId="cateId"
    @success="addOrEditSuccess"
  />
</template>

<script setup>
import { ref, onMounted, computed, nextTick } from "vue";
import { getCategories } from "@/api/categories.js";
import {
  getCategoriesParam,
  addAttrVals,
  deleteParams,
} from "@/api/params.js";
import { ElMessage, ElMessageBox } from "element-plus";
import addOrEditParam from "./addOrEditParam.vue";

const emit = defineEmits(["keyup.enter"]);
const cateList = ref([]); // 分类数据
const parentCateList = ref([]); //父级分类列表
const cascaderProps = {
  // 指定级联选择器的配置对象
  expandTrigger: "hover",
  value: "cat_id",
  label: "cat_name",
  children: "children",
};
const selectedKeys = ref([]); // 选中父级分类ID数组
const activeTabName = ref("many"); // 被激活的页签
const manyTableData = ref([]); // 动态属性数据
const onlyTableData = ref([]); // 静态属性数据
const saveTagInput = ref(null);
const isShowVisible = ref(false); // 添加/编辑对话框的显示隐藏
const attrInfo = ref({});
const titleText = ref("");
const attrId = ref([]);

const isBtnDisabled = computed(() => {
  if (selectedKeys.value.length !== 3) {
    return true;
  } else {
    return false;
  }
});
// 当前选中的商品分类ID(计算属性)
const cateId = computed(() => {
  if (selectedKeys.value.length === 3) {
    return selectedKeys.value[2];
  } else {
    return null;
  }
});

onMounted(() => {
  getCateList();
});

// 获取商品分类
const getCateList = async () => {
  const data = await getCategories();
  cateList.value = data;
};

// 选择商品分类
const parentCateChange = () => {
  if (selectedKeys.value.length !== 3) {
    selectedKeys.value = [];
    manyTableData.value = [];
    onlyTableData.value = [];
    return;
  }
  getParamsData();
};

// 获取参数列表数据
const getParamsData = async () => {
  // 根据所选分类ID和当前所处的面板获取对应的参数
  const data = await getCategoriesParam(cateId.value, activeTabName.value);

  data.forEach((item) => {
    item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
    // 控制文本框的显示与隐藏
    item.inputVisible = false;
    // 文本框输入的值
    item.inputValue = "";
  });

  if (activeTabName.value === "many") {
    manyTableData.value = data;
  } else {
    onlyTableData.value = data;
  }
};

// tab页签点击事件
const handleTabClick = () => {
  nextTick(() => {
    getParamsData();
  });
};

// 删除对应的参数可选项
const removeParams = (row, index) => {
  row.attr_vals.splice(index, 1);
  saveAttrVals(row);
};

// 将对attr_vals的操作保存到数据库
const saveAttrVals = async (row) => {
  const obj = {
    attr_name: row.attr_name,
    attr_sel: row.attr_sel,
    attr_vals: row.attr_vals.join(" "),
  };
  const data = await addAttrVals(cateId.value, row.attr_id, obj);

  ElMessage.success("编辑参数选项成功");
  getParamsData();
};

// 文本框失去焦点，或者按enter触发
const handleInputConfirm = (row) => {
  if (row.inputValue.trim().length === 0) {
    row.inputValue = "";
    row.inputVisible = false;
    return;
  }
  //提交添加的参数/属性
  row.attr_vals.push(row.inputValue.trim());
  row.inputValue = "";
  row.inputVisible = false;
  saveAttrVals(row);
};

// 点击添加tag按钮展示文本框
const showInput = (row) => {
  attrId.value = [];
  attrId.value.push(row.attr_id)
  row.inputVisible = true;
  // 让文本框自动获得焦点
  // $nextTick方法的作用：当页面上的元素重新被渲染之后，才会指定回调函数中的代码
  nextTick(() => {
    saveTagInput.value && saveTagInput.value.focus();
  });
};

// 点击编辑按钮
const handleAddOrEdit = (row) => {
  isShowVisible.value = true;
  if (activeTabName.value === "many") {
    titleText.value = "动态参数";
  } else {
    titleText.value = "静态属性";
  }
  attrInfo.value = row;
};

// 删除
const handleDelete = (id) => {
  ElMessageBox.confirm("此操作将永久删除该参数, 是否继续?", "删除参数", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await deleteParams(cateId.value, id);
    ElMessage.success("删除成功");
    getParamsData();
  });
};

// 添加/编辑弹框关闭后回调函数
const addOrEditSuccess = () => {
  isShowVisible.value = false;
  attrInfo.value = {};
  getParamsData();
};
</script>

<style lang="scss" scoped>
.cat-opt {
  margin: 15px 0;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 150px;
  margin-left: 10px;
}
.btn-new-tag {
  margin-left: 10px;
}
</style>
